﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

using System.Xml;
using System.Xml.Serialization;

namespace ecdl.demo.model.expression {
    public enum WordZoomMode {
        [XmlEnum(Name = "Percentage")]
        Percentage,
        [XmlEnum(Name = "PageWidth")]
        PageWidth,
        [XmlEnum(Name = "TextWidth")]
        TextWidth,
        [XmlEnum(Name = "WholePage")]
        WholePage
    }

    public class WordZoomExpression : WordExpression {
        private static readonly string POS = "Der Zoom ist korrekt eingestellt.";
        private static readonly string NEG = "Der Zoom ist nicht korrekt eingestellt";

        public double Percentage { get; set; }
        public WordZoomMode ZoomMode { get; set; }

        public override ExpressionState Evaluate(ExpressionContext context) {
            if (context.HasContext<WordprocessingDocument>()) {
                WordprocessingDocument document = context.GetContext<WordprocessingDocument>();
                var settingPart = document.MainDocumentPart.DocumentSettingsPart;
                if (isValidZoom(settingPart.Settings.Zoom)) {
                    return Success(POS, NEG);

                }
            }
            return FailInvalidContext();
        }

        private bool isValidZoom(Zoom zoom) {
            switch (ZoomMode) {
                case WordZoomMode.Percentage:
                    return (zoom.Val == null || zoom.Val.Value == PresetZoomValues.None) 
                                && Double.Parse(zoom.Percent) == Percentage;
                case WordZoomMode.PageWidth:
                    return zoom.Val != null && zoom.Val.Value == PresetZoomValues.BestFit;
                case WordZoomMode.TextWidth:
                    return zoom.Val != null && zoom.Val.Value == PresetZoomValues.TextFit;
                case WordZoomMode.WholePage:
                    return zoom.Val != null && zoom.Val.Value == PresetZoomValues.FullPage;
                default:
                    return false;
            }
        }

        protected override ExpressionState Evaluate(IEnumerable<OpenXmlElement> contextElements) {
            //ignore this
            return null;
        }
    }

    public class WordZoomExpressionDTO : ExpressionDTO {
        public WordZoomExpressionDTO() : base(typeof(WordZoomExpression)) {
            Console.WriteLine();
        }

        [XmlAttribute("percentage")]
        public double Percentage { get; set; }
        [XmlAttribute("mode")]
        public WordZoomMode ZoomMode { get; set; }
    }
}
